﻿using JumpKick.HttpLib;
using Newtonsoft.Json;
using SharpEncrypt4.Lib;
using SharpEncrypt4l_Lib;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.Runtime.Caching;
using YiHaoHospitalPlatform.Model;

namespace YiHaoHospitalPlatform
{
    public sealed class CommitDepartmentInstance
    {
        #region 局部变量
        /// <summary>
        /// 部门数据缓存
        /// </summary>
        private static MemoryCache DepartmentCache =  MemoryCache.Default;
        /// <summary>
        /// 要提交的部门列表
        /// </summary>
        private static List<Department> departmentList = new List<Department>();
        /// <summary>
        /// 公钥
        /// </summary>
        private static string publicKey;
        /// <summary>
        /// 平台接口地址
        /// </summary>
        private static string platformUrl;
        /// <summary>
        /// 平台分配的机构代码
        /// </summary>
        private static string orgId;
        /// <summary>
        /// 缓存时间
        /// </summary>
        private static int cacheMinutes=600;
        /// <summary>
        /// 检索部门信息action
        /// </summary>
        static Action QueryDepartmentAction;
        /// <summary>
        /// 成功action
        /// </summary>
        private static Action<string> LoopCommitAction = new Action<string>(commitDepartment);
        /// <summary>
        /// 失败action
        /// </summary>
        private static Action<WebException> FailLoopCommitAction = new Action<WebException>(RetryCommitDepartment);
        #endregion

        #region 单利模式
        private static readonly Lazy<CommitDepartmentInstance> instance = new Lazy<CommitDepartmentInstance>(() =>
        {
            if (publicKey == null)
            {
                publicKey = ConfigurationManager.AppSettings["publicKey"];
            }
            if (platformUrl == null)
                platformUrl = ConfigurationManager.AppSettings["platform_url"];
            if (orgId == null)
                orgId = ConfigurationManager.AppSettings["org_id"];
            cacheMinutes = int.Parse(ConfigurationManager.AppSettings["department_cache_minutes"]);
            return new CommitDepartmentInstance();
        });
        private CommitDepartmentInstance() { }
        public static CommitDepartmentInstance Instance
        {
            get
            {
                return instance.Value;
            }
        }
        #endregion

        /// <summary>
        /// 设置本地检索数据的action
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public CommitDepartmentInstance setQueryDepartmentAction(Action action)
        {
            QueryDepartmentAction = action;
            return Instance;
        }
        /// <summary>
        /// 向服务器提交数据，只需调用一次，内部会循环调用获取数据的方法
        /// </summary>
        /// <param name="departments">部门列表</param>
        /// <returns></returns>
        public bool StartCommitDepartments(List<Department> departments)
        {
            if (QueryDepartmentAction == null)
                throw new Exception("请先设置QueryPatientAction");
            if (departments != null)
                //组织要提交的数据
                foreach (Department department in departments)
                {
                    //判断缓存中是否有该数据
                    Department cache = DepartmentCache[department.DepartmentId] as Department;
                    if (cache == null)
                    {
                        department.isNew = true;
                        departmentList.Add(department);
                        AddCache(department);
                    }
                    else if (!cache.Equals(department))
                    {
                        department.isNew = false;
                        departmentList.Add(department);
                        AddCache(department);
                    }
                }

            commitDepartment(null);
            return true;
        }

        private static void RetryCommitDepartment(WebException ex)
        {
            commitDepartment(null);
        }
        /// <summary>
        /// 递归调用，向服务器逐条提交数据
        /// </summary>
        private static void commitDepartment(string commitSuccess)
        {
            if (departmentList.Count > 0 && commitSuccess != null)
                departmentList.RemoveAt(0);
            if (departmentList.Count > 0)
            {
                string json = JsonConvert.SerializeObject(departmentList[0]);
                Console.WriteLine(json+"当前线程数："+ Process.GetCurrentProcess().Threads.Count);
                string encryptPatient = EncryptProvider.RSAEncrypt(RSAKeyConvert.RSAPublicKeyJava2DotNet(publicKey), json);
                Http.Post(platformUrl).Form(new { orgId = orgId, data = encryptPatient })
                    .OnSuccess(LoopCommitAction)
                    .OnFail(FailLoopCommitAction)
                    .Go();
            }
            else
            {
                QueryDepartmentAction.BeginInvoke(null, null);
            }
        }

        /// <summary>
        /// 向缓存中添加数据
        /// </summary>
        /// <param name="department"></param>
        private void AddCache(Department department)
        {
            Department cache = DepartmentCache[department.DepartmentId] as Department;
            if (cache != null)
                DepartmentCache.Remove(department.DepartmentId);
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinutes);//取得或设定值，这个值会指定是否应该在指定期间过后清除
            DepartmentCache.Set(department.DepartmentId, department, policy);
        }
    }
}
